{% extends "base.html" %}

{% block title %}导出报表 - 管理后台{% endblock %}

{% block content %}
<div class="export-container">
    <!-- 页面标题 -->
    <div class="export-header">
        <h1 class="export-title">报表导出</h1>
        <p class="export-subtitle">选择需要导出的报表类型</p>
    </div>

    <!-- 导出选项卡片 -->
    <div class="export-grid">
        {% for export_type in export_types %}
        <div class="export-card" data-type="{{ export_type.key }}">
            <div class="export-icon">
                {% if export_type.key == 'all' %}📊
                {% elif export_type.key == 'orders' %}📋
                {% elif export_type.key == 'users' %}👥
                {% elif export_type.key == 'products' %}📦
                {% elif export_type.key == 'revenue' %}💰
                {% elif export_type.key == 'production' %}🏭
                {% else %}📄{% endif %}
            </div>
            <h3 class="export-name">{{ export_type.name }}</h3>
            <p class="export-description">{{ export_type.description }}</p>
            <button class="export-btn" onclick="exportReport('{{ export_type.key }}')">
                导出报表
            </button>
            <div class="export-status" id="status-{{ export_type.key }}"></div>
        </div>
        {% endfor %}
    </div>

    <!-- 日期范围选择 -->
    <div class="date-range-section">
        <h3>导出时间范围</h3>
        <div class="date-inputs">
            <div class="date-group">
                <label for="start-date">开始日期:</label>
                <input type="date" id="start-date" name="start-date">
            </div>
            <div class="date-group">
                <label for="end-date">结束日期:</label>
                <input type="date" id="end-date" name="end-date">
            </div>
            <div class="date-presets">
                <button type="button" class="preset-btn" onclick="setDateRange(7)">最近7天</button>
                <button type="button" class="preset-btn" onclick="setDateRange(30)">最近30天</button>
                <button type="button" class="preset-btn" onclick="setDateRange(90)">最近90天</button>
            </div>
        </div>
    </div>

    <!-- 导出历史 -->
    <div class="export-history">
        <h3>最近导出记录</h3>
        <div class="history-list" id="export-history">
            <div class="history-item">
                <div class="history-info">
                    <span class="history-type">订单报表</span>
                    <span class="history-date">2024-01-15 14:30</span>
                </div>
                <button class="download-btn" onclick="downloadFile('report_orders_20240115.xlsx')">下载</button>
            </div>
            <div class="history-item">
                <div class="history-info">
                    <span class="history-type">收入报表</span>
                    <span class="history-date">2024-01-14 09:15</span>
                </div>
                <button class="download-btn" onclick="downloadFile('report_revenue_20240114.xlsx')">下载</button>
            </div>
        </div>
    </div>
</div>

<style>
.export-container {
    padding: 2rem;
    max-width: 1200px;
    margin: 0 auto;
}

.export-header {
    text-align: center;
    margin-bottom: 3rem;
}

.export-title {
    font-size: 2.5rem;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 0.5rem;
}

.export-subtitle {
    font-size: 1.1rem;
    color: #7f8c8d;
    margin-bottom: 0;
}

/* 导出卡片样式 */
.export-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
    margin-bottom: 3rem;
}

.export-card {
    background: white;
    border-radius: 16px;
    padding: 2rem;
    text-align: center;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    border: 1px solid #f0f0f0;
    transition: all 0.3s ease;
    position: relative;
}

.export-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.export-card.exporting {
    opacity: 0.7;
    pointer-events: none;
}

.export-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
    display: block;
}

.export-name {
    font-size: 1.5rem;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 1rem;
}

.export-description {
    color: #7f8c8d;
    margin-bottom: 2rem;
    line-height: 1.6;
}

.export-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    padding: 0.75rem 2rem;
    border-radius: 25px;
    font-weight: 600;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.export-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.export-btn:active {
    transform: translateY(0);
}

.export-status {
    margin-top: 1rem;
    font-size: 0.9rem;
    min-height: 1.5rem;
}

.export-status.success {
    color: #27ae60;
}

.export-status.error {
    color: #e74c3c;
}

.export-status.loading {
    color: #3498db;
}

/* 日期范围样式 */
.date-range-section {
    background: white;
    border-radius: 16px;
    padding: 2rem;
    margin-bottom: 3rem;
    box-shadow: 0 2px 15px rgba(0,0,0,0.06);
}

.date-range-section h3 {
    font-size: 1.5rem;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 1.5rem;
    text-align: center;
}

.date-inputs {
    display: grid;
    grid-template-columns: 1fr 1fr auto;
    gap: 2rem;
    align-items: end;
}

.date-group {
    display: flex;
    flex-direction: column;
}

.date-group label {
    font-weight: 500;
    color: #2c3e50;
    margin-bottom: 0.5rem;
}

.date-group input {
    padding: 0.75rem;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    font-size: 1rem;
    transition: border-color 0.3s ease;
}

.date-group input:focus {
    outline: none;
    border-color: #667eea;
}

.date-presets {
    display: flex;
    gap: 0.5rem;
    align-items: end;
}

.preset-btn {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.9rem;
}

.preset-btn:hover {
    background: #e9ecef;
    border-color: #adb5bd;
}

/* 导出历史样式 */
.export-history {
    background: white;
    border-radius: 16px;
    padding: 2rem;
    box-shadow: 0 2px 15px rgba(0,0,0,0.06);
}

.export-history h3 {
    font-size: 1.5rem;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 1.5rem;
    text-align: center;
}

.history-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.history-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    border-radius: 8px;
    background: #f8f9fa;
    transition: background 0.3s ease;
}

.history-item:hover {
    background: #e9ecef;
}

.history-info {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.history-type {
    font-weight: 500;
    color: #2c3e50;
}

.history-date {
    font-size: 0.9rem;
    color: #7f8c8d;
}

.download-btn {
    background: #27ae60;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.9rem;
}

.download-btn:hover {
    background: #219a52;
    transform: translateY(-1px);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 0.5rem;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .export-container {
        padding: 1rem;
    }
    
    .export-title {
        font-size: 2rem;
    }
    
    .export-grid {
        grid-template-columns: 1fr;
    }
    
    .date-inputs {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
    
    .date-presets {
        justify-content: center;
    }
    
    .history-item {
        flex-direction: column;
        gap: 1rem;
        text-align: center;
    }
}

/* 成功动画 */
@keyframes success-pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

.export-card.success {
    animation: success-pulse 0.6s ease-in-out;
}
</style>

<script>
// 导出报表函数
async function exportReport(type) {
    const card = document.querySelector(`[data-type="${type}"]`);
    const statusDiv = document.getElementById(`status-${type}`);
    const exportBtn = card.querySelector('.export-btn');
    
    // 获取日期范围
    const startDate = document.getElementById('start-date').value;
    const endDate = document.getElementById('end-date').value;
    
    // 显示加载状态
    card.classList.add('exporting');
    exportBtn.innerHTML = '<div class="loading-spinner"></div>导出中...';
    statusDiv.innerHTML = '正在生成报表...';
    statusDiv.className = 'export-status loading';
    
    try {
        // 构建请求URL
        let url = `/admin/export?export=${type}`;
        if (startDate) url += `&start_date=${startDate}`;
        if (endDate) url += `&end_date=${endDate}`;
        
        const response = await fetch(url);
        const data = await response.json();
        
        if (response.ok && data.download_url) {
            // 显示成功状态
            statusDiv.innerHTML = '报表生成成功！';
            statusDiv.className = 'export-status success';
            card.classList.add('success');
            
            // 自动下载文件
            setTimeout(() => {
                window.open(`http://localhost:8000${data.download_url}`, '_blank');
            }, 1000);
            
            // 添加到历史记录
            addToHistory(type, data.download_url);
            
        } else {
            throw new Error(data.error || '导出失败');
        }
        
    } catch (error) {
        // 显示错误状态
        statusDiv.innerHTML = `导出失败: ${error.message}`;
        statusDiv.className = 'export-status error';
        
    } finally {
        // 恢复按钮状态
        setTimeout(() => {
            card.classList.remove('exporting', 'success');
            exportBtn.innerHTML = '导出报表';
        }, 2000);
    }
}

// 设置日期范围
function setDateRange(days) {
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);
    
    document.getElementById('start-date').value = startDate.toISOString().split('T')[0];
    document.getElementById('end-date').value = endDate.toISOString().split('T')[0];
}

// 下载文件
function downloadFile(filename) {
    window.open(`http://localhost:8000/admin/export/download/${filename}`, '_blank');
}

// 添加到历史记录
function addToHistory(type, downloadUrl) {
    const historyList = document.getElementById('export-history');
    const filename = downloadUrl.split('/').pop();
    const date = new Date().toLocaleString('zh-CN');
    
    const typeNames = {
        'all': '完整报表',
        'orders': '订单报表',
        'users': '用户报表',
        'products': '商品报表',
        'revenue': '收入报表',
        'production': '生产报表'
    };
    
    const newItem = document.createElement('div');
    newItem.className = 'history-item';
    newItem.innerHTML = `
        <div class="history-info">
            <span class="history-type">${typeNames[type] || type}</span>
            <span class="history-date">${date}</span>
        </div>
        <button class="download-btn" onclick="downloadFile('${filename}')">下载</button>
    `;
    
    historyList.insertBefore(newItem, historyList.firstChild);
    
    // 限制历史记录数量
    if (historyList.children.length > 5) {
        historyList.removeChild(historyList.lastChild);
    }
}

// 页面加载时设置默认日期范围
document.addEventListener('DOMContentLoaded', function() {
    setDateRange(30); // 默认最近30天
    
    // 添加卡片悬停效果
    const cards = document.querySelectorAll('.export-card');
    cards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
});
</script>
{% endblock %}